document.addEventListener('DOMContentLoaded', () => {
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    if (!isLoggedIn) {
        window.location.href = "../test登录界面/登录.html";
        return;
    }

    const currentUsername = localStorage.getItem('currentUsername');
    const userInfoKey = `userInfo-${currentUsername}`;
    let userInfo = JSON.parse(localStorage.getItem(userInfoKey)) || {};

    const logoutLink = document.getElementById('logout-link');
    const usernameDisplay = document.getElementById('username-display');
    const userAvatar = document.querySelector('.user-avatar');
    const currentUsernameElement = document.getElementById('current-username');
    const currentPhone = document.getElementById('current-phone');
    const currentEmail = document.getElementById('current-email');
    const currentGender = document.getElementById('current-gender');
    const currentBirthday = document.getElementById('current-birthday');
    const currentZodiac = document.getElementById('current-zodiac');
    const currentPlaces = document.getElementById('current-places');
    const currentSignature = document.getElementById('current-signature');
    const editUsername = document.getElementById('edit-username');
    const editAvatar = document.getElementById('edit-avatar');
    const editPhone = document.getElementById('edit-phone');
    const editEmail = document.getElementById('edit-email');
    const editGender = document.getElementById('edit-gender');
    const editBirthday = document.getElementById('edit-birthday');
    const editSignature = document.getElementById('edit-signature');
    const placesContainer = document.getElementById('places-container');
    const avatarPreview = document.getElementById('avatar-preview');
    const saveAvatarBtn = document.querySelector('.save-avatar-btn');
    const saveOtherInfoBtn = document.querySelector('.save-other-info-btn');
    const fileUploadBtn = document.getElementById('file-upload-btn');
    const fileNameSpan = document.getElementById('file-name');

    const places = ['Bayi Square', 'Tengwang Pavilion', 'Wenquan Zen Temple', 'Shengjin Pagoda', 'Jiangxi Art Museum', 'Wanshou Palace'];
    places.forEach(place => {
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.id = `place-${place}`;
        checkbox.name = 'places';
        checkbox.value = place;

        const label = document.createElement('label');
        label.htmlFor = `place-${place}`;
        label.textContent = place;

        const div = document.createElement('div');
        div.appendChild(checkbox);
        div.appendChild(label);
        placesContainer.appendChild(div);
    });

    if (isLoggedIn) {
        usernameDisplay.textContent = userInfo.username;
        userAvatar.src = userInfo.avatar || '../images/Default Avatar.jpg';
        currentUsernameElement.textContent = userInfo.username;
        currentPhone.textContent = userInfo.phone || 'Not Set';
        currentEmail.textContent = userInfo.email || 'Not Set';
        currentGender.textContent = userInfo.gender || 'Not Set';
        currentBirthday.textContent = userInfo.birthday || 'Not Set';
        currentZodiac.textContent = userInfo.zodiac || 'Not Set';
        currentPlaces.textContent = userInfo.places ? userInfo.places.join(', ') : 'Not Set';
        currentSignature.textContent = userInfo.signature || 'Not Set';
        logoutLink.style.display = 'inline-block';
        editUsername.value = userInfo.username;
        editPhone.value = userInfo.phone || '';
        editEmail.value = userInfo.email || '';
        editGender.value = userInfo.gender || 'Confidential';
        editBirthday.value = userInfo.birthday || '';
        editSignature.value = userInfo.signature || '';
    } else {
        window.location.href = "../test登录界面/登录.html";
    }

    logoutLink.addEventListener('click', () => {
        localStorage.setItem('isLoggedIn', 'false');
        localStorage.removeItem('currentUsername');
        usernameDisplay.textContent = 'Not Logged In';
        userAvatar.src = '../images/Default Avatar.jpg';
        window.location.href = "../test登录界面/登录.html";
    });

    fileUploadBtn.addEventListener('click', () => {
        editAvatar.click();
    });

    editAvatar.addEventListener('change', () => {
        const file = editAvatar.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                avatarPreview.src = e.target.result;
                avatarPreview.style.display = 'block';
            };
            reader.readAsDataURL(file);
            fileNameSpan.textContent = file.name;
        } else {
            fileNameSpan.textContent = 'No file chosen';
        }
    });

    if (saveAvatarBtn) {
        saveAvatarBtn.addEventListener('click', () => {
            const file = editAvatar.files[0];
            if (!file) {
                alert('Please select an avatar!');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const imgSrc = e.target.result;
                userAvatar.src = imgSrc;

                userInfo.avatar = imgSrc;
                localStorage.setItem(userInfoKey, JSON.stringify(userInfo));
                alert('Avatar saved successfully!');
            };
            reader.readAsDataURL(file);
        });
    }

    if (saveOtherInfoBtn) {
        saveOtherInfoBtn.addEventListener('click', () => {
            const username = editUsername.value.trim();
            const phone = editPhone.value.trim();
            const email = editEmail.value.trim();
            const gender = editGender.value.trim();
            const birthday = editBirthday.value.trim();
            const signature = editSignature.value.trim();
            const selectedPlaces = Array.from(document.querySelectorAll('input[name="places"]:checked')).map(input => input.value);

            if (!username || !phone || !email) {
                alert('Please fill in all required fields!');
                return;
            }

            const zodiac = calculateZodiac(birthday);

            userInfo = {
                ...userInfo,
                username,
                phone,
                email,
                gender,
                birthday,
                zodiac,
                signature
            };

            if (selectedPlaces.length > 0) {
                userInfo.places = selectedPlaces;
            }

            localStorage.setItem(userInfoKey, JSON.stringify(userInfo));
            alert('Personal information saved successfully!');
            updateUserInfoDisplay(userInfo);
        });
    }

    // Auto-update zodiac when birthday changes
    editBirthday.addEventListener('change', () => {
        const birthday = editBirthday.value.trim();
        const zodiac = calculateZodiac(birthday);
        currentZodiac.textContent = zodiac;
        userInfo.zodiac = zodiac;
        localStorage.setItem(userInfoKey, JSON.stringify(userInfo));
    });

    function updateUserInfoDisplay(userInfo) {
        usernameDisplay.textContent = userInfo.username;
        currentUsernameElement.textContent = userInfo.username;
        currentPhone.textContent = userInfo.phone || 'Not Set';
        currentEmail.textContent = userInfo.email || 'Not Set';
        currentGender.textContent = userInfo.gender || 'Not Set';
        currentBirthday.textContent = userInfo.birthday || 'Not Set';
        currentZodiac.textContent = userInfo.zodiac || 'Not Set';
        currentPlaces.textContent = userInfo.places ? userInfo.places.join(', ') : 'Not Set';
        currentSignature.textContent = userInfo.signature || 'Not Set';
    }

    function calculateZodiac(birthday) {
        if (!birthday) return '';
        const [year, month, day] = birthday.split('/').map(Number);
        if (!month || !day) return '';

        const zodiacs = [
            { name: 'Capricorn', start: { month: 12, day: 22 }, end: { month: 12, day: 31 } },
            { name: 'Capricorn', start: { month: 1, day: 1 }, end: { month: 1, day: 19 } },
            { name: 'Aquarius', start: { month: 1, day: 20 }, end: { month: 2, day: 18 } },
            { name: 'Pisces', start: { month: 2, day: 19 }, end: { month: 3, day: 20 } },
            { name: 'Aries', start: { month: 3, day: 21 }, end: { month: 4, day: 19 } },
            { name: 'Taurus', start: { month: 4, day: 20 }, end: { month: 5, day: 20 } },
            { name: 'Gemini', start: { month: 5, day: 21 }, end: { month: 6, day: 21 } },
            { name: 'Cancer', start: { month: 6, day: 22 }, end: { month: 7, day: 22 } },
            { name: 'Leo', start: { month: 7, day: 23 }, end: { month: 8, day: 22 } },
            { name: 'Virgo', start: { month: 8, day: 23 }, end: { month: 9, day: 22 } },
            { name: 'Libra', start: { month: 9, day: 23 }, end: { month: 10, day: 22 } },
            { name: 'Scorpio', start: { month: 10, day: 23 }, end: { month: 11, day: 21 } },
            { name: 'Sagittarius', start: { month: 11, day: 22 }, end: { month: 12, day: 21 } }
        ];

        for (const zodiac of zodiacs) {
            if ((month === zodiac.start.month && day >= zodiac.start.day) || 
                (month === zodiac.end.month && day <= zodiac.end.day)) {
                return zodiac.name;
            }
        }
        return '';
    }
});